# -*- coding: UTF-8 -*-

from .BaseService import BaseService

class WechatMediaMessageInterpretService(BaseService):

    def interpretQrcodeImg(self, uin, msgId):
        userinfoDetailDO = self.core.loader.instance('do', 'UserinfoDetail').get(uin)
        if userinfoDetailDO is None:
            return self.core.lib.outputobj(False, '用户登录信息获取失败')

        url = '%s/webwxgetmsgimg' % userinfoDetailDO.login_url
        params = {'MsgID': msgId, 'skey': userinfoDetailDO.skey, 'type': 'slave'}
        request = self.core.loader.lib('request', transport_core = True)
        responseRes = request.sGet(mSession = userinfoDetailDO.session, url = url, params = params, stream = True, headers = self.core.config.DEFAULT_HEADER)
        if not responseRes.success:
            return responseRes

        saveRes = self._savePic(msgId, responseRes.data)
        if not saveRes.success:
            return saveRes

        try:
            return self._interpretQrcodePath(saveRes.data)
        except Exception as e:
            return self.core.lib.outputobj(False, '图片解析发生异常：%s' % str(e))


    def _savePic(self, msgId, response):
        mPath = self.core.loader.module('os.path')
        if not hasattr(self.core.config, 'PICTURE_SAVE_PATH') or not mPath.exists(self.core.config.PICTURE_SAVE_PATH):
            return self.core.lib.outputobj(False, '图片保存目录不存在')

        mTime = self.core.loader.module('time')
        picturePath = '%s%s_%s%s' % (self.core.config.PICTURE_SAVE_PATH, mTime.strftime('%Y%m%d'), msgId, self.core.config.QRCODE_SAVE_EXT)
        with open(picturePath, 'wb') as f:
            for stream in response.iter_content(chunk_size = 1024):
                f.write(stream)

        return self.core.lib.outputobj(True, '图片保存成功', picturePath)


    def _interpretQrcodePath(self, picturePath):
        paths = []
        mZbar = self.core.loader.module('zbar')
        mImage = self.core.loader.module('PIL.Image')
        scanner = mZbar.ImageScanner()
        scanner.parse_config('enable')
        
        with mImage.open(picturePath).convert('L') as img:
            w, h = img.size
            zimg = mZbar.Image(w, h, 'Y800', img.tobytes())
            scanner.scan(zimg)
            for s in zimg:
                if str(s.type) == 'QRCODE' and str(s.data):
                    paths.append(str(s.data))

        return self.core.lib.outputobj(True, '解析成功', paths)
